﻿using System;
using System.Collections.Generic;
using System.Linq;
using DAL;
using BLL;
using System.IO;

using Microsoft.AspNet.Membership.OpenAuth;
using System.Web;
using System.Web.Security;

namespace IAATO.Account
{
    public partial class Manage : System.Web.UI.Page
    {
        protected string SuccessMessage
        {
            get;
            private set;
        }

        protected bool CanRemoveExternalLogins
        {
            get;
            private set;
        }

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Déterminer les sections à afficher
                var hasLocalPassword = OpenAuth.HasLocalPassword(User.Identity.Name);
                setPassword.Visible = !hasLocalPassword;
                changePassword.Visible = hasLocalPassword;

                CanRemoveExternalLogins = hasLocalPassword;

                // Afficher le message de réussite
                var message = Request.QueryString["m"];
                if (message != null)
                {
                    // Enlever la chaîne de requête de l'action
                    Form.Action = ResolveUrl("~/Manage.aspx");

                    SuccessMessage =
                        message == "ChangePwdSuccess" ? "Votre mot de passe a été modifié."
                        : message == "SetPwdSuccess" ? "Votre mot de passe a été défini."
                        : message == "RemoveLoginSuccess" ? "La connexion externe a été supprimée."
                        : String.Empty;
                    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                }
            }

            if (!HttpContext.Current.User.IsInRole("Admin"))
            {
                sectionJeu.Visible = false;
            }

        }

        protected void setPassword_Click(object sender, EventArgs e)
        {
            if (IsValid)
            {
                var result = OpenAuth.AddLocalPassword(User.Identity.Name, password.Text);
                if (result.IsSuccessful)
                {
                    Response.Redirect("~/Manage.aspx?m=SetPwdSuccess");
                }
                else
                {

                    ModelState.AddModelError("NewPassword", result.ErrorMessage);

                }
            }
        }


        public IEnumerable<OpenAuthAccountData> GetExternalLogins()
        {
            var accounts = OpenAuth.GetAccountsForUser(User.Identity.Name);
            CanRemoveExternalLogins = CanRemoveExternalLogins || accounts.Count() > 1;
            return accounts;
        }

        public void RemoveExternalLogin(string providerName, string providerUserId)
        {
            var m = OpenAuth.DeleteAccount(User.Identity.Name, providerName, providerUserId)
                ? "?m=RemoveLoginSuccess"
                : String.Empty;
            Response.Redirect("~/Manage.aspx" + m);
        }


        protected static string ConvertToDisplayDateTime(DateTime? utcDateTime)
        {
            // Vous pouvez modifier cette méthode afin de convertir la date/heure UTC par la référence et la mise en forme
            // d'affichage souhaitées. Ici, nous la convertissons au fuseau horaire et à la mise en forme du serveur
            // sous la forme d'une chaîne date courte et heure complète, à l'aide de la culture du thread actuelle.
            return utcDateTime.HasValue ? utcDateTime.Value.ToLocalTime().ToString("G") : "[never]";
        }


        protected void lkbGenerer_Click(object sender, EventArgs e)
        {
            ActiviteService activiteService = new ActiviteService(new ActiviteManager(), new SiteManager());
            ActiviteSiteLinkService activiteSiteLinkService = new ActiviteSiteLinkService(new ActiviteSiteLinkManager());
            SiteService siteService = new SiteService(new SiteManager(), new ActiviteManager(), new CreneauService(new CreneauManager()));
            ZoneService zoneService = new ZoneService(new ZoneManager());
            CompagnieService compagnieService = new CompagnieService(new CompagnieManager());
            CreneauService creneauService = new CreneauService(new CreneauManager());
            NavireService navireService = new NavireService(new NavireManager());
            ProgrammeService programmeService = new ProgrammeService(new ProgrammeManager());
            CategorieService categorieService = new CategorieService(new CategorieManager());

            foreach (ACTIVITE activite in activiteService.getAllActivites())
            {
                activiteService.deleteActivite(activite.ID);
            }

            foreach (ACTIVITE_SITE_LINK activiteSiteLink in activiteSiteLinkService.getAllActiviteSiteLinks())
            {
                activiteSiteLinkService.deleteActiviteSiteLink(activiteSiteLink.ACTIVITEID, activiteSiteLink.SITEID);
            }

            foreach (COMPAGNIE compagnie in compagnieService.getAllCompagnies())
            {
                compagnieService.deleteCompagnie(compagnie.ID);
            }

            foreach (CRENEAU creaneau in creneauService.getAllCreneaux())
            {
                creneauService.deleteCreneau(creaneau.ID);
            }

            foreach (NAVIRE navire in navireService.getAllNavires())
            {
                navireService.deleteNavire(navire.ID);
            }

            foreach (PROGRAMME programme in programmeService.getAllProgrammes())
            {
                programmeService.deleteProgramme(programme.ID);
            }

            foreach (SITE site in siteService.getAllSites())
            {
                siteService.deleteSite(site.ID);
            }

            foreach (ZONE zone in zoneService.getAllZones())
            {
                zoneService.deleteZone(zone.ID);
            }

            foreach (CATEGORIE categorie in categorieService.getAllCategories())
            {
                categorieService.deleteCategorie(categorie.ID);
            }

            foreach (MembershipUser user in Membership.GetAllUsers())
            {
                if (user.UserName != HttpContext.Current.User.Identity.Name)
                {
                    Membership.DeleteUser(user.UserName);
                }
            }
            
            // PARSAGE EXCEL 
            string file = "C:\\Database\\shipList.csv";
            string line;
            string[] currentLine;

            FileStream aFile = new FileStream(file, FileMode.Open);
            StreamReader sr = new StreamReader(aFile);

            while ((line = sr.ReadLine()) != null)
            {
                currentLine = line.Split(new char[] { ';' });

                COMPAGNIE compagnie = compagnieService.getCompagnieByNom(currentLine[1]);
                if (compagnie == null)
                    compagnie = compagnieService.createCompagnie(currentLine[1]);

                int compagnieId = compagnie.ID;

                CATEGORIE categorie = categorieService.getCategorieByNom(currentLine[2]);
                if (categorie == null)
                    categorie = categorieService.createCategorie(currentLine[2], 100);

                int categorieId = categorie.ID;

                NAVIRE newNavire = navireService.createNavire(currentLine[0], categorieId, 500, currentLine[4], currentLine[5], compagnieId, currentLine[3]);

                string navireUserName = newNavire.NOM + "_" + newNavire.ID;
                Membership.CreateUser(navireUserName, navireUserName + "password", null);
                Roles.AddUserToRole(navireUserName, "Navire");
            }


            // SITE LAT LNG ZONE ACT
            file = "C:\\Database\\siteList.csv";
            aFile = new FileStream(file, FileMode.Open);
            sr = new StreamReader(aFile);

            while ((line = sr.ReadLine()) != null)
            {
                currentLine = line.Split(new char[] { ';' });

                ZONE zone = zoneService.getZoneByNom(currentLine[3]);
                if (zone == null)
                    zone = zoneService.createZone(currentLine[3]);

                int zoneId = zone.ID;

                /*ACTIVITE activite = activiteService.getActiviteByNom(currentLine[4]);
                if (activite == null)
                    activite = activiteService.createActivite(currentLine[4]);

                int activiteId = activite.ID;*/
                SITE site = siteService.createSite(zoneId, currentLine[0], double.Parse(currentLine[1].Replace('.', ',')), double.Parse(currentLine[2].Replace('.', ',')));

                //activiteSiteLinkService.createActiviteSiteLink(activiteId, site.ID);
            }

            Response.Redirect("~/Manage.aspx");

            
            
            // FIN PARSAGE EXCEL
        }
    }
}